import React from 'react';
import { inject, observer} from 'mobx-react';
import allStore from '../../stores';
import {Synergy} from 'weaPortal';
import {WeaTableNew} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import {
    WeaTop,
    WeaTab,
    WeaLeftRightLayout,
    WeaRightMenu,
    WeaPopoverHrm,
    WeaTools,
    WeaErrorPage,
    WeaLocaleProvider,
    WeaDropdown,
    WeaHelpfulTip
} from 'ecCom';
import {Button} from 'antd';
import ListLeftTree from './ListLeftTree';
import WfForward from '../../asyncComps/Forward';
import TagTypeSelectDialog from '../../asyncComps/TagTypeSelectDialog';
import {Condition,getAdButtons} from './ListCondition';
import FormModifyLog from '../../asyncComps/ModifyLog';
import * as Util from '../../util/listUtil';
import BatchSubmit from '../../asyncComps/BatchSubmit';
import SendSms from '../../asyncComps/SendSms';//新建短信
import SendEmail from '../../asyncComps/SendEmail';
import {verifySupervise} from "../../util/superviseUtil";
import {toJS} from "mobx";
//新建邮件
const getLabel = WeaLocaleProvider.getLabel;
const { ButtonSelect } = WeaDropdown;


@inject('wfListMineStore')

@observer
class ListMine extends React.Component {
    constructor(props) {
        super(props);
        window.__currentStore = props.wfListMineStore;
    }
    doInit(props){
        allStore.wfGlobalStore.setCurrentListSymbol('ListMine');
        const { location,wfListMineStore } = props;
        wfListMineStore.setUrlParams(location.query);
        wfListMineStore.initDatas({method:"all"});
        wfListMineStore.doSearch({loadDefTab:true});
        _ListenerCtrl.bind();
    }
    componentDidMount() {
        this.doInit(this.props);
        if(window.location.pathname.indexOf('/spa/workflow/index') > -1)
            document.title = this.props.wfListMineStore.title;
            // const { hover } = this.props.wfListMineStore;
            this.timerID=setTimeout(()=>{ 
                $(".wf_attention_div_btn").on("mouseover mouseout",function(event){
                    const str = $(this).attr('id').substr($(this).attr('id').indexOf('_'))
                    if(event.type == "mouseover"){  
                     jQuery("#attentionSpan"+str).css("display","block")
                    }else if(event.type == "mouseout"){
                     jQuery("#attentionSpan"+str).css("display","none")
                    }
                   })
             },1000)
    }
    componentDidUpdate(){
        // const { hover } = this.props.wfListMineStore;
        this.timerID=setTimeout(()=>{ 
            $(".wf_attention_div_btn").on("mouseover mouseout",function(event){
                const str = $(this).attr('id').substr($(this).attr('id').indexOf('_'))
                if(event.type == "mouseover"){  
                 jQuery("#attentionSpan"+str).css("display","block")
                }else if(event.type == "mouseout"){
                 jQuery("#attentionSpan"+str).css("display","none")
                }
               })
         },1000)
      }
    componentWillReceiveProps(nextProps) {
        if(this.props.location.key !== nextProps.location.key) {
            const { wfListMineStore } = this.props;
            wfListMineStore.clearStatus();
            this.doInit(nextProps);
        }
    }
    shouldComponentUpdate(nextProps,nextState) {
        return true;
    }
    componentWillUnmount(){
        const { wfListMineStore } = this.props;
        wfListMineStore.clearStatus();
        _ListenerCtrl.unbind();
        clearTimeout(this.timerID);
    }
    setShowSearchAd=bool=>{this.props.wfListMineStore.setShowSearchAd(bool)};
    hideSearchAd=()=> this.props.wfListMineStore.setShowSearchAd(false);
    onSearch=v=>{this.props.wfListMineStore.doSearch()};

    render() {
        const { wfListMineStore } = this.props;
        const {title,loading,urlParams,tableStore,topTab,topTabCount,searchParams,showSearchAd,form,showBatchSupervisor,emailVisible,fwquery,smsParams,smsVisible,smsVisible_mount,emailVisible_mount} = wfListMineStore;
        const formParams = form.getFormParams() || {};
        const loadingTable = tableStore.loading;
        const contentDiv = <div style={{height: '100%'}}>
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@y49j71`}
                leftStyle={{paddingRight:300}}
                needCalLsPaddingRight={true}
                buttonsAd={getAdButtons(wfListMineStore, this.props && this.props.ecId || '')}
                searchType={['base','advanced']}
                searchsBaseValue={formParams.requestname}
                setShowSearchAd={this.setShowSearchAd}
                hideSearchAd={this.hideSearchAd}
                searchsAd={
                    <Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@h1ek2b`} listStore={wfListMineStore} />
                }
                showSearchAd={showSearchAd}
                datas={topTab}
                selectedKey={searchParams.viewcondition}
                counts={topTabCount}
                onSearch={this.onSearch}
                onSearchChange={v=>{wfListMineStore.appendFormFields({requestname:{value:v}})}}
                keyParam="viewcondition"  //主键
                countParam="groupid" //数量
                onChange={this.switchTab} />
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@us5gqb`} 
                comsWeaTableStore={tableStore}
                rowKey={this.getRowKey}
                register_table={wfListMineStore.reLoad}
                hasOrder={true}
                needScroll={true} 
                //uniqueId={true}--和rowKey重复
                getColumns={this.getColumns}
            />
        </div>;
        //是否显示左侧树
        const WeaTopContent = urlParams.needTree !== "false" ? 
        <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@j5lx0x`} defaultShowLeft={true}
            leftCom={<ListLeftTree ecId={`${this && this.props && this.props.ecId || ''}_ListLeftTree@av4m73`} listStore={wfListMineStore} />}
        >{ contentDiv }</WeaLeftRightLayout> : 
        <div>{ contentDiv }</div>;
        let menuDatas = this.getRightMenu();
        let icon = Util.getTopIcon(urlParams);
        let iconBgcolor = Util.getTopIconBgColor(urlParams);
        let buttons = this.getButtons();
        return (
            <div>
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@nrgnvj`} 
                    collectParams={{favname:title, favouritetype:2}}
                    datas={menuDatas}
                >
                {
                    urlParams.needTop !== "false" ? 
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@b5fxd0`}
                        title={title}
                        loading={loading || loadingTable}
                        icon={icon}
                        iconBgcolor={iconBgcolor}
                        buttons={buttons}
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={menuDatas}
                    >{ WeaTopContent }</WeaTop> : 
                    <div>{ WeaTopContent }</div>
                }
                <WfForward ecId={`${this && this.props && this.props.ecId || ''}_WfForward@skcafr`}/>
                </WeaRightMenu>
                <FormModifyLog ecId={`${this && this.props && this.props.ecId || ''}_FormModifyLog@ql4ppt`} />
                <Synergy ecId={`${this && this.props && this.props.ecId || ''}_Synergy@a21z9h`} pathname='/workflow/listMine' requestid="-1" />
                <TagTypeSelectDialog ecId={`${this && this.props && this.props.ecId || ''}_TagTypeSelectDialog@d6peas`} curStore={allStore.wfFollowTypeSettingStore} refresh={wfListMineStore.doSearch}/>

                <BatchSubmit ecId={`${this && this.props && this.props.ecId || ''}_BatchSubmit@uuzlsj`}
                        visible={showBatchSupervisor}
                        onSubmit={this.batchSupervisorEvent}
                        onCancel={this.batchSubmitCancel}
                        onSubmitText={getLabel(21223,'督办')}
                    />
                {
                    smsVisible_mount && <SendSms ecId={`${this && this.props && this.props.ecId || ''}_SendSms@28wvyk`} params={mobx.toJS(smsParams)} visible={smsVisible} closeFun={()=>{wfListMineStore.setSmsVisible(false)}}/>
                }
                {
                    emailVisible_mount && <SendEmail ecId={`${this && this.props && this.props.ecId || ''}_SendEmail@0qdgyp`}  visible={emailVisible} fromCb={true} fwquery={mobx.toJS(fwquery)} closeFun={()=>{wfListMineStore.setEmailVisible(false)}}/>
                }
            </div>
        )
    }

    batchSubmitCancel = ()=>{this.props.wfListMineStore.setShowBatchSupervisor(false)}
    getRowKey =(record,index) =>{
        return `${record.requestid}_${record.userid||""}`;
    }

    getColumns = (columns) => {
        const columnsJS = toJS(columns);
        columnsJS.forEach(col => {
            if(col.dataIndex === "unoperators"){
                const title = (
                    <span>
                        <span title={col.title}>
                            { col.title }
                        </span>
                        {<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@baa56v@${col.dataIndex}`} style={{ marginLeft: 5 }} title={getLabel(516719,"可在【个性化设置】中设置未操作者的显示类型")} placement="top" />}
                    </span>
            )
                col.title = title;
            }
        });
        return columnsJS;
    }

    switchTab = (tabKey) => {
        const {wfListMineStore} = this.props;
        const {topTab} = wfListMineStore;
        wfListMineStore.setShowSearchAd(false);
        wfListMineStore.doSearch({
            viewcondition: tabKey
        });
    }
    getRightMenu(){
        const { wfListMineStore } = this.props;
        const { tableStore,operBtnKey,sharearg } = wfListMineStore;
        const selectedRowKeysAllPages = tableStore.selectedRowKeysAllPages;
        let btns = [];
        btns.push({
            key: "search",
    		icon: <i className='icon-workflow-Right-menu--search'/>,
            content:getLabel(197,'搜索'),
            onClick: key =>{
                wfListMineStore.doSearch();
    		    wfListMineStore.setShowSearchAd(false);
            }
        });
        btns.push({
            key: "batchAttention",
            icon: <i className='icon-coms-Subscribe'/>,
            content: getLabel(503955,'批量关注'),
                disabled: operBtnKey !== "batchAttention" || selectedRowKeysAllPages.length <= 0,
            onClick: this.batchAttention.bind(this,selectedRowKeysAllPages)
        });
        /*btns.push({
            key: "batchSupervisor",
            icon: <i className='icon-coms-daiban'/>,
            content: getLabel(84561,'批量督办'),
            disabled: operBtnKey !== "batchSupervisor" || selectedRowKeys.length <= 0,
            onClick: this.batchSupervisor.bind(this)
        });*/
        btns.push({
            key:"colSet",
    		icon: <i className='icon-workflow-Right-menu-Custom'/>,
            content:getLabel(382660,'显示列定制'),
            onClick: key =>{
                tableStore.setColSetVisible(true);
    		    tableStore.tableColSet(true);
            }
        });
    	return btns;
    }

    batchSupervisorEvent = (remark = '') => {
        const { wfListMineStore } = this.props;
        const { tableStore } = wfListMineStore;
        const selectedRowKeys = tableStore.selectedRowKeys;

        let requestids = wfListMineStore.getSingleRequestid();//点击每一行后面督办按钮的情况

        if(requestids == ''){
            requestids = selectedRowKeys;
        }

        let params = {requestids,remark};
        verifySupervise(requestids,remark,()=> {
            wfListMineStore.doSupervise(params);
            wfListMineStore.setShowBatchSupervisor(false);
        });
    }

    //批量督办
    batchSupervisor = () => {
        const { wfListMineStore } = this.props;
        wfListMineStore.setShowBatchSupervisor(true,'');
    }

    //批量关注
    batchAttention = () => {
        const { wfListMineStore } = this.props;
        const { sharearg ,tableStore} = wfListMineStore;
        const {selectedRowKeysAllPages} = tableStore;
        let idarr = selectedRowKeysAllPages.map(v => {
            const arr = v.split("_");
            const requestid = arr[0];
            return requestid;
        });
        let requestIds = idarr.join(",");
        allStore.wfFollowTypeSettingStore.isSingle = false
        allStore.wfFollowTypeSettingStore.followTypeSelectShow = true
        allStore.wfFollowTypeSettingStore.FollowRequestid = requestIds
        // if(idarr.length==1){
        //     window.followTypeSettingStore.getWorkflowAttentionTypeSet(idarr[0])
        // }else{
        //     window.followTypeSettingStore.getWorkflowAttentionTypeSet()
        // }
    }

    getButtons() {
        const { wfListMineStore } = this.props;
        const { tableStore } = wfListMineStore;
        const selectedRowKeysAllPages = tableStore.selectedRowKeysAllPages;
        let btns = [];
        btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@a2g775@batchAttention`} type="primary" disabled={selectedRowKeysAllPages.length <= 0} onClick={()=>{this.batchAttention()}}>{getLabel(503955,'批量关注')}</Button>)
        return btns;
    }
}

export default WeaTools.tryCatch(React, 
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@0vnidp`} msg={ props.error ? props.error : getLabel(383324,' 对不起，该页面异常，请联系管理员 ')+'！'} />,
    {error: ""}
)(ListMine);